package com.dmall.scf.utils

import java.sql.Connection

import com.mchange.v2.c3p0.ComboPooledDataSource

/**
  * Created with IntelliJ IDEA.
  * Author: wangxuexing
  * Description:MySQL连接池管理类
  * Date: Created in 2018-11-17 12:43
  */
object MySQLPoolManager {
  var mysqlManager: MysqlPool = _

  def getMysqlManager: MysqlPool = {
    synchronized {
      if (mysqlManager == null) {
        mysqlManager = new MysqlPool
      }
    }
    mysqlManager
  }

  class MysqlPool extends Serializable {
    private val cpds: ComboPooledDataSource = new ComboPooledDataSource(true)
    try {
      cpds.setJdbcUrl(SparkUtils.getEnv.mySqlConfig.url)
      cpds.setDriverClass("com.mysql.jdbc.Driver")
      cpds.setUser(SparkUtils.getEnv.mySqlConfig.user)
      cpds.setPassword(SparkUtils.getEnv.mySqlConfig.password)
      cpds.setMinPoolSize(4)
      cpds.setMaxPoolSize(4)
      cpds.setAcquireIncrement(2)
      cpds.setMaxStatements(50)
    } catch {
      case e: Exception => e.printStackTrace()
    }

    def getConnection: Connection = {
      try {
        cpds.getConnection()
      } catch {
        case ex: Exception => {
          println(s"url: ${SparkUtils.getEnv.mySqlConfig.url}, user: ${SparkUtils.getEnv.mySqlConfig.user}")
          ex.printStackTrace()
        }
          null
      }
    }

    def close(): Unit = {
      try {
        cpds.close()
      } catch {
        case ex: Exception =>
          ex.printStackTrace()
      }
    }
  }

}
